package com.palmshop.online.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;

import com.palmshop.online.service.impl.WXServiceImpl;
import com.palmshop.util.SignUtil;

/**
 * 确认来自微信服务器的请求
 * @author Administrator
 *
 */
@Controller
public class WXController extends HttpServlet{
	private static final long serialVersionUID = 4323197796926899691L;
	
	private final Logger logger = Logger.getLogger(this.getClass());

    /**
     * 确认请求来自微信服务器
     */
//	@RequestMapping("/checkToken")
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
		logger.info("开始checkToken...");
        
        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");
        
        logger.info("paremeters..."+signature+";timestamp："+timestamp+"；nonce："+nonce+";echostr:"+echostr);
        

        PrintWriter out = response.getWriter();
        
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            out.print(echostr);
        }
        logger.info("结束checkToken...");
        out.close();
        out = null;
    }

    /**
     * 处理微信服务器发来的消息
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	
    	logger.info("checkToken...post>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    	
    	
    	// 消息的接收、处理、响应
        // 将请求、响应的编码均设置为UTF-8（防止中文乱码）
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 调用核心业务类接收消息、处理消息
        String respXml = WXServiceImpl.processRequest(request);
        logger.info("checkToken>>>>>>>postEND>>>>>>>>>>>>>>"+respXml);

        // 响应消息
        PrintWriter out = response.getWriter();
        out.print(respXml);
        out.close();
    }


}